<template>
  <!-- 当点击 取消按钮 时，关闭弹窗 -->
  <el-dialog
    :title="$t('printBoxCode.reprint')"
    :visible.sync="visible"
    width="65%"
    top="4vh"
    :append-to-body="true"
    @close="clearDialog()"
    v-loading="loding"
    :close-on-click-modal="false"
  >
    <ele-form
      v-model="dialogfrom"
      v-bind="formConfig"
      v-loading="loading"
      ref="form"
    ></ele-form>
    <barcode-print
      :barcodeInfo="barcodeInfo"
      ref="print"
      :isPrint="false"
      :key="time"
      v-if="Object.keys(barcodeInfo).length > 0"
    ></barcode-print>
    <div slot="footer" class="dialog-footer">
      <el-button @click="clearDialog()">{{ $t("common.cancel") }}</el-button>
      <el-button
        v-if="dialogfrom.type == 1"
        type="primary"
        @click="handleSave"
        >{{ $t("common.save") }}</el-button
      >
      <el-button
        v-else
        :disabled="!dialogfrom.quantity"
        type="primary"
        @click="handleRequest"
        >{{ $i18n.t("mesCapacityCodePrinting.print") }}</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import BarcodePrint from "@/components/barcodePrint/barcodePrint";

import {
  checkCapacityCode, //校验是否已经生成对应类型容量码
  templateType, //获取生码分类
  getProdByOrder, //根据订单获取型号
  selectCommonProduceRelByProduce, //根据型号、分类获取生码规则接口
  getCapacityCodeList, //获取容量/数量列表接口,
  mesProdCapacitycodeReprint, //补打审核列表查询
  reprintCapacitySel, //补打查询获取已打印容量码数据
  reprintCapacitySelList,
  insert,
} from "@/api/print/mesCapacityCode";
import { printTemplateInfoName } from "@/api/barcodeprint/mesBarcodeprintHistory";
import sys from "@/config";
export default {
  name: "barcodePrintingAddModel",
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.form.resetForm();
        });
        this.barcodeInfo = {};
      }
    },
  },
  props: {
    title: {
      type: String,
      default: "",
    },
  },
  components: { BarcodePrint },
  data() {
    let that = this;
    return {
      loding: false,
      time: 0,
      formConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: "right",
        formDesc: {
          orderCode: {
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.orderCode"),
            layout: 8,
            disabled: true,
            attrs: {
              stepStrictly: true,
              controlsPosition: "right",
              min: 1,
            },
          },
          printSort: {
            type: "select",
            label: $i18n.t("mesCapacityCodePrinting.printSort"),
            layout: 8,
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const params = {};
              const list = await templateType(params);
              return list.data.result;
            },
            on: {
              change(val) {
                that.dialogfrom.printSort = val;
                (that.formConfig.formDesc.goodsCode.options = async (data) => {
                  const params = {
                    orderCode: data.orderCode,
                  };
                  const list = await getProdByOrder(params);
                  that.goodsCodeList = list.data.result;
                  return list.data.result;
                }),
                  that.changeCode();
              },
            },
            disabled: (data) => {
              return data.type == 1;
            },
          },
          goodsCode: {
            //型号
            type: "select",
            label: $i18n.t("mesCapacityCodePrinting.goodsCode"),
            layout: 8,
            prop: {
              value: "prodCode",
              text: "prodName",
            },
            options: async (data) => {
              const params = {
                orderCode: data.orderCode,
              };
              const list = await getProdByOrder(params);
              that.goodsCodeList = list.data.result;
              return list.data.result;
            },
            slots: {
              default(h, options) {
                let data = that.goodsCodeList;
                if (data && data.length > 0) {
                  return data.map((option) =>
                    h("el-option", { attrs: { value: option.prodCode } }, [
                      h("span", { style: { float: "left" } }, option.prodName),
                      h(
                        "span",
                        {
                          style: {
                            float: "right",
                            color: "#8492a6",
                            fontSize: "13px",
                          },
                        },
                        option.prodCode
                      ),
                    ])
                  );
                } else {
                  return [];
                }
              },
            },
            on: {
              change(val) {
                that.dialogfrom.goodsCode = val;
                let goodsCodeList = that.goodsCodeList;
                let goodsCode = goodsCodeList.find((item) => {
                  return item.prodCode == val;
                });
                if (goodsCode) {
                  that.dialogfrom.productType = goodsCode.productType;
                }

                that.changeCode();
              },
            },
            disabled: (data) => {
              return data.type == 1;
            },
          },
          printCount: {
            type: "select",
            label: $i18n.t("mesCapacityCodePrinting.volume"),
            layout: 8,
            prop: {
              value: "count",
              text: "count",
            },
            options: async (data) => {
              if (data.printCountList) {
                return data.printCountList;
              } else {
                return [];
              }
            },
            on: {
              change(val) {
                that.changeCount(val);
              },
            },
            required: true,
            disabled: false,
          },
          quantity: {
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.barcodeQty"),
            layout: 12,
            disabled: true,
            required: true,
            vif(data) {
              return data.printCount != "";
            },
          },
          startBarCode: {
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.startBarCode"),
            layout: 24,
            required: true,
            vif(data) {
              return data.printCount != "";
            },
          },
          endBarCode: {
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.endBarCode"),
            layout: 24,
            required: true,
            vif(data) {
              return data.printCount != "";
            },
          },
        },
      },
      barcodeInfo: {},
      dialogfrom: {},
      visible: false,
      loading: false,
      list: [],
    };
  },
  methods: {
    // 初始化
    init(params) {
      this.dialogfrom = params;
      this.barcodeInfo = params;
      this.visible = true;
      this.dialogfrom.printQuantity = this.dialogfrom.quantity; //条码数量=计划数量
      this.formConfig.formDesc.printCount.options = params.printCountList;
      this.reprintSel();
    },
    changeCount(count) {
      this.reprintSel(count);
    },
    //类型型号选择处理
    changeCode() {
      let createData = this.dialogfrom;
      let check = {
        orderCode: createData.orderCode,
        prodCode: createData.goodsCode,
        productType: createData.productType,
        capacityType: createData.printSort,
      };
      //当分类和型号都存在时获取效验容量码是否生成
      if (check.capacityType && check.prodCode) {
        this.loading = true;
        checkCapacityCode(check).then((res) => {
          this.loading = false;
          if (res.data.result) {
            getCapacityCodeList(check).then((res) => {
              const { success, result } = res.data;
              if (success) {
                let tableData = result.barCodeResult;

                this.dialogfrom.barcodePrintTemp = result.barcodePrintTemp;
                this.dialogfrom.barcodePrintTempCode =
                  result.barcodePrintTempCode;

                let printCount = [];
                tableData.forEach((item) => {
                  if (item.hasPrintNum > 0) {
                    printCount.push({ count: item.count });
                  }
                });
                this.formConfig.formDesc.printCount.options = printCount;
              } else {
                this.formConfig.formDesc.printCount.options = [];
              }
            });
          } else {
            this.dialogfrom.printCount = "";
            this.dialogfrom.startBarCode = "";
            this.dialogfrom.endBarCode = "";
            this.formConfig.formDesc.printCount.options = [];
          }
        });
      }
    },
    /**
     * @author bing
     * @since 2022-11-17 14:44:33
     *  获取补打信息
     */
    async reprintSel(count) {
      const params = {
        orderCode: this.dialogfrom.orderCode,
        prodCode: this.dialogfrom.goodsCode,
        capacityType: this.dialogfrom.printSort,
        count: count,
      };
      this.loading = true;
      const res = await reprintCapacitySel(params);
      if (res.data.result.templateName) {
        let resBarcodePrint = await printTemplateInfoName({
          templateName: res.data.result.templateName,
        });
        this.barcodeInfo = {
          ...this.barcodeInfo,
          ...resBarcodePrint.data.result[0],
        };
      }
      this.$nextTick(() => {
        this.dialogfrom = {
          startBarCode: "",
          endBarCode: "",
          ...this.dialogfrom,
          ...res.data.result,
        };
        this.loading = false;
      });
    },
    clearDialog() {
      this.visible = false;
      this.$emit("refreshList");
    },
    // 点击打印按钮
    handleRequest() {
      this.$refs.form.handleSubmitForm();
      this.$refs.form.validate().then((valid) => {
        this.initSplitPrint();
      });
    },
    //预览打印
    async initSplitPrint() {
      //获取打印模板信息
      const {
        orderCode,
        prodCode,
        printSort,
        startBarCode,
        endBarCode,
        barcodePrintTemp,
        barcodePrintTempCode,
      } = this.dialogfrom;
      const data = {
        orderCode: orderCode,
        prodCode: prodCode,
        capacityType: printSort,
        startBarCode: startBarCode,
        endBarCode: endBarCode,
      };
      reprintCapacitySelList(data).then((res) => {
        if (res.data.success) {
          let list = res.data.result,
            info = this.barcodeInfo;

          let obj = {
            barcodePrintTempCode: info.barcodePrintTempCode,
            printType: 1,
            barcodePrintTemp: info.barcodePrintTemp,
            barCodeResult: list,
            barcodePrintTemp: barcodePrintTemp,
            barcodePrintTempCode: barcodePrintTempCode,
          };

          localStorage.splitPrint = JSON.stringify(obj);

          this.clearDialog();
          this.$router.push("/splitPrint");
        }
      });
    },

    // 点击保存按钮
    handleSave() {
      this.$refs.form.validate().then((valid) => {
        if (!valid) {
          const { orderCode, startBarCode, endBarCode, goodsCode, printSort } =
            this.dialogfrom;
          const data = {
            orderCode,
            prodCode: goodsCode,
            capacityType: printSort,
            startBarcode: startBarCode,
            endBarcode: endBarCode,
          };
          insert(data).then((res) => {
            this.visible = false;
            this.$parent.$refs.repairPrintTables.refresh();
          });
        }
      });
    },
  },
};
</script>
